

var DY_MenuManager = function(target, data, openOrderCallback){
    var self = this;
    this.listTable = target.find('table.menu-table');
    this.scrollWrap = target.find('.scroll-wrap');
    this.menus = {};
    this.subtotalEl = target.find('div.count').eq(0);
    this.feeEl = target.find('div.count').eq(1);
    this.totalEl = target.find('div.count').eq(2);
    this.openOrderCallback = openOrderCallback;
    this.count = {
        s: 0,
        f: 10
    };
    this.isNull = function(){
        for(var m in self.menus){
            return false;
        }
        return true;
    };
    this.getTrueTotal = function(){
        return (this.count.s).toFixed(2);
    };
    this.updateCount = function(addCount){
        this.count.s = 0;
        var cookieJSON = {list:[]};
        for(var m in self.menus){
            self.count.s += self.menus[m].cost;
            cookieJSON.list.push({
                id: m,
                name: self.menus[m].name,
                price: self.menus[m].price,
                cost: self.menus[m].price * self.menus[m].quantity,
                quantity: self.menus[m].quantity
                //option: {'229':['19']},
            });
        }
        $.cookie('dy_orderList', $.toJSON(cookieJSON));
        if(self.count.s > 1000){
            self.count.f = 100;
        }
        
        self.subtotalEl.children('span').text(self.count.s.toFixed(2) + ' 元');
        self.feeEl.children('span').text(self.count.f.toFixed(2) + ' 元');
        self.totalEl.children('span').text((self.count.s + self.count.f).toFixed(2) + ' 元');
        
        target.find('#form-confirm-products').val($.toJSON(cookieJSON));
    };
    this.addRow = function(id, name, price, quantity, showMsg){
        if(!isLog){DY.msg('请先登录。'); return;}
        if(!isOpenOrderPanel){this.openOrderCallback();}
    
        if(!self.menus[id]){
            quantity = parseFloat(quantity || 1);
            var el = $('<tr><td class="name">' + name + '</td><td class="quantity">'
                    +'<ul class="select-qua"><li class="lt"><a href="#" class="remove">-</a></li><li class="md"><input type="text" class="ipt_num" value="' + quantity + '"/></li><li class="rt"><a href="#" class="add">+</a></li></ul>'
                    +'</td><td class="cost"><span>' + (price * quantity).toFixed(2) + '</span></td><td class="cancel"><a href="#">X</a></td></tr>')
                    .hover(function(e){
                        el.addClass('over');
                    },function(e){
                        el.removeClass('over');
                    });
            var costEl = el.find('td.cost span');
           
            var cancelEl = el.find('td.cancel a').click(function(e){
                self.removeRow(id);
                return false;
            });
            new dySelectQuantity(el.find('.select-qua'), function(val){
                var cost = val * price
                costEl.html(cost.toFixed(2));
                self.menus[id].cost = cost;
                self.updateCount();
            });
            self.listTable.append(el);

        }else{
            quantity = parseFloat(quantity || 1);
            quantity = self.menus[id].quantity + quantity;
            
            var el = self.menus[id].el;
            var numEl = el.find('td.quantity input').val(quantity);
            DY.checkNumber(numEl);
            quantity = numEl.val();
            el.find('td.cost span').html((price * quantity).toFixed(2));
            //DY.msg('此菜式已经添加过咯');
            self.menus[id].el.stop(true, true).animate({opacity:0}, 300).animate({opacity:1}, 600);
        }
        
        self.menus[id] = {
            el: el,
            name: name,
            price: price,
            cost: price * quantity,
            quantity: quantity * 1
        };
        
        
        self.checkScroll();
        self.updateCount();
        if(showMsg){DY.msg('添加成功')};
    };
    this.removeRow = function(id){
        self.menus[id].el.animate({opacity:0}, {
            speed: 500,
            complete: function(){
                self.menus[id].el.remove();
                self.menus[id] = null;
                delete self.menus[id];
                self.updateCount();
            }
        });
        self.checkScroll();
    };
    this.removeAll = function(){
        for(var m in self.menus){
            self.removeRow(m);
        }
    };
    //check if has scrollbar
    this.checkScroll = function(){
        if(self.scrollWrap[0].scrollHeight > self.scrollWrap[0].offsetHeight){
            self.scrollWrap.addClass('scroll');
        }else{
            self.scrollWrap.removeClass('scroll');
        }
    };
    //init
    if(data){
        for( var i = 0; i < data.length; i++ ){
            this.addRow(data[i].id, data[i].name, data[i].price, data[i].quantity);
        }
    }
};

var DY_DetailViewer = function(menuListDom, viewerDom){
    var self = this;
    this.menuList = menuListDom;
    this.viewer = viewerDom;
    this.mask = $('#idx_menu_mask');
    this.viewer.find('.hd a').click(function(){
        self.back();
        return false;
    });
    
    this.show = function(id, e){
        //this.menuList.hide();
        DY.loading();
        $.get('index.php?route=product/product&product_id=' + id, function(o){
            self.viewer.children('.bd').html(o);
            //lightBox
            //self.viewer.find('div.pic a').lightBox(); 
            
            //image show
            self.viewer.find('div.pic .small a').click(function(e){
                if(!$(this).hasClass('noimage')){
                    self.viewer.find('div.pic .big img').attr('src', $(this).attr('href'));
                }
                return false;
            });
            
            new dySelectQuantity(self.viewer.find('.select-qua'));
            DY.loading(false);
            if($('html, body')[0].scrollTop > 330){
                $('html, body').animate({scrollTop:330});
            }
            //self.viewer.css({opacity:0, top:100}).show().animate({top:0, opacity:1}, function(){});  //animate
            self.viewer.show();
            self.mask.show();
        });
    };
    
    this.back = function(){
        this.menuList.height('auto').show();
        /*
        this.viewer.animate({top:300, opacity:0}, function(){
            $(this).hide();
        });
        */
        this.viewer.hide();
        this.mask.hide();
        DY.hash('mid', null, true);
    };
}

$(window).ready(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() > 340){
            //$('#side-nav').addClass('side-nav_onfloat');
        }else{
            //$('#side-nav').removeClass('side-nav_onfloat');
        }
    });
    
    isOpenOrderPanel = false;
    
    $('.slideshow').dySlideshow();
    
    //Menu List
    $('#idx_menu .dy-menu').dyMenu();
    categoryPanel = $('#idx_menu .category-panel');
    $('.category-tab').click(function(e){
        var tab = $(this);
        if(!tab.data('products')){
            DY.loading();
            $.get('index.php?route=product/category&path=' + tab.data('cid'), function(o){
                tab.data('products', o);
                categoryPanel.children('ul').html(o);
                categoryPanel.find('.menu-item').hover(function(e){
                    $(this).addClass('menu-item-over');
                },function(e){
                    $(this).removeClass('menu-item-over');
                });
                DY.loading(false);
            });
        }else{
            categoryPanel.children('ul').html(tab.data('products'));
            categoryPanel.find('.menu-item').hover(function(e){
                $(this).addClass('menu-item-over');
            },function(e){
                $(this).removeClass('menu-item-over');
            });
        }
        return false;
    });
    $.get('index.php?route=product/category&path=' + category_id, function(o){
        categoryPanel.children('ul').html(o);
    });
    
    var openOrderPanel = function(){
        $('#side-member .start-order').animate({height:0}, function(){
            $(this).hide();
            $('#side-order').show();
            $('#side-member').animate({height:900});
        });
        $('#side-feature, #side-help').fadeOut(1000);
        isOpenOrderPanel = true;
    };
    var openLoginPanel = function(){
        $('#side-member').find('.nologin').animate({top:-150})
        $('#side-member').find('.login').show().animate({top:0}, function(){
            //$(this).hide();
            //$('#side-order').show();
            //$('#side-member').animate({height:650});
        });
    };
    var checkAddress = function(){
        return $('input[name=address]:checked').length > 0
    };
    var menuManager = new DY_MenuManager($('#side-order'), selectedMenu, openOrderPanel);
    var detailViewer = new DY_DetailViewer($('#idx_menu'), $('#idx_detail'));
    
    
    
    //menu list
    $('#idx_menu').click(function(e){
        var target = $(e.target);
        if(target.parent().hasClass('order') && target[0].tagName.toLowerCase() == 'a'){
            menuManager.addRow(target.data('mid'), target.data('name'), parseFloat(target.data('price')), 1, true);
        }
        if(target.parent().parent().hasClass('pic')){
            var data = target.parent().parent().parent().find('.order a').data();
            detailViewer.show(data['mid'], e);
        }
        if(target.parent()[0].tagName.toLowerCase() == 'h4'){
            var data = target.parent().parent().find('.order a').data();
            detailViewer.show(data['mid'], e);
        }
        return false;
    });
    
    $('#idx_detail .bd').click(function(e){
        var target = $(e.target);
        if(target.hasClass('btn-order') && target[0].tagName.toLowerCase() == 'a'){
            if(target.hasClass('half-size')){//half size
                menuManager.addRow(target.data('mid'), target.data('name'), parseFloat(target.data('price')), 1, true);
            }else{
                menuManager.addRow(target.data('mid'), target.data('name'), parseFloat(target.data('price')), $('#idx_detail .bd .ipt_num').val(), true);
            }
        }
        return false;
    });
    
    //member panel
    var memberTab = new dyTabmenu($('#side-member .dy-tab'), function(i, menu, pn){
        if(i===1 && !checkAddress()){
            DY.msg('请选择送餐地址。');
            memberTab.active(0);
        }
    });
    $('#side-member').find('a.lnk-login').click(function(e){
        openLoginPanel();
        return false;
    });
    $('#side-member').find('a.lnk-order').click(function(e){
        if(isLog){
            if(hasAddress){
                openOrderPanel();
            }else{
                location.href = "index.php?route=account/address/update&address_id=" + hasAddressId;
            }
        }else{
            openLoginPanel();
        }
        return false;
    })
    
    $('#btn-order-s1').click(function(e){
        if(!checkAddress()){
            DY.msg('请选择送餐地址。');
        }else{
            $.get('index.php?route=checkout/cart/updateShipping&' + $('#form-order-info').serialize());
            memberTab.active(1);
        }
        return false;

    });
    $('#btn-order-s2').click(function(e){
        $.get('index.php?route=checkout/cart/checkOrder&' + $('#form-order-info').serialize() + '&total=' + menuManager.getTrueTotal(), function(o){
            //console.log(o);
            if(o === '1'){
                DY.msg('您选择时间段的预定人数已满，请选择其他时间段。');
            }else if(o === '2'){
                DY.msg('您选择时间段的已过，请选择其他时间段。');
            }else if(o === '3'){
                DY.msg('您的订餐总价少于最低消费额哦。');
            }else if(menuManager.isNull()){
                DY.msg('您的菜单为空，请选择。');
            }else {
                $('#form-confirm').submit();
            }
        });
        return false;
    });
    $('.btn-clearall').click(function(e){
        menuManager.removeAll();
        return false;
    });
    //cancel order
    $('.btn-cancel-order').click(function(e){
        $.cookie('dy_orderList', null);
        location.reload(true);
    });

	
	//featured
	var featuredModule = $('#side-feature');
	featuredModule.find('.hd a').click(function(e){
		buildFeatured();
		return false;
	});
	var buildFeatured = function(){
		if(featuredMenu){
			var idx = [parseInt(Math.random(1) * featuredMenu.length), parseInt(Math.random(1) * featuredMenu.length)];
			featuredModule.find('.products').slideUp(300, function(){
				$(this).remove();
			});
			ul = $('<ul class="products clearfix">')
			for(var i=0;i<idx.length;i++){
                with({i:i}){
                    var m = featuredMenu[idx[i]];
                    var li = $('<li>').data('mid', m['product_id']).click(function(e){
                        detailViewer.show(li.data('mid'), e);
                        DY.hash('mid', li.data('mid'));
                        return false;
                    });
                    li.append('<a href="#mid=' + m['product_id'] + '" class="pic"><img src="' + m['thumb'] + '" /></a>');
                    li.append('<a href="#mid=' + m['product_id'] + '" class="name">' + m['name'] + '</a>');
                    li.appendTo(ul);
                }
            }
			ul.appendTo(featuredModule.find('.bd'));
		}
	};
	buildFeatured();
	
    
    if(isLog && selectedMenu && selectedMenu.length>0 && userid == $.cookie('dy_userid')){
        openOrderPanel();
        if(checkAddress()){
            memberTab.active(1);
        }
    }
    $.cookie('dy_userid', userid);

    if(DY.hash('mid') && DY.hash('mid') > 0 ){
        detailViewer.show(DY.hash('mid'));
    }
    
 }); 